
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>如何使用getopt()函数解析参数 | 安生</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="最近在写程序的过程中，把一部分时间都花费在程序对参数的处理上。今天听了学长说到getopt函数，才发现原来c里面还有一个专门解决参数处理的函数，查询了相关资料，这里简单总结一下。
使用int main( int argc, char *argv[] )或int main( int argc, char **argv )时，系统将把用户输入的参数通过argc和argv引入程序中，argc为参数的个数">
<meta property="og:type" content="article">
<meta property="og:title" content="如何使用getopt()函数解析参数">
<meta property="og:url" content="http://localhost/2014/07/18/如何使用getopt-函数解析参数/index.html">
<meta property="og:site_name" content="安生">
<meta property="og:description" content="最近在写程序的过程中，把一部分时间都花费在程序对参数的处理上。今天听了学长说到getopt函数，才发现原来c里面还有一个专门解决参数处理的函数，查询了相关资料，这里简单总结一下。
使用int main( int argc, char *argv[] )或int main( int argc, char **argv )时，系统将把用户输入的参数通过argc和argv引入程序中，argc为参数的个数">
<meta property="og:updated_time" content="2016-04-11T08:53:56.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="如何使用getopt()函数解析参数">
<meta name="twitter:description" content="最近在写程序的过程中，把一部分时间都花费在程序对参数的处理上。今天听了学长说到getopt函数，才发现原来c里面还有一个专门解决参数处理的函数，查询了相关资料，这里简单总结一下。
使用int main( int argc, char *argv[] )或int main( int argc, char **argv )时，系统将把用户输入的参数通过argc和argv引入程序中，argc为参数的个数">
  
    <link rel="alternative" href="/atom.xml" title="安生" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  <link rel="stylesheet" href="/css/style.css">
  <link href="//fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <!--[if lt IE 9]><script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7/html5shiv.min.js"></script><![endif]-->
  
</head>
<body>
<div id="container">
  <div id="wrap">
    <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">安生</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="http://www.baidu.com/baidu" method="get" accept-charset="utf-8" class="search-form">
          <input type="search" name="word" maxlength="20" class="search-form-input" placeholder="Search">
          <input type="submit" value="" class="search-form-submit">
          <input name=tn type=hidden value="bds">
          <input name=cl type=hidden value="3">
          <input name=ct type=hidden value="2097152">
          <input type="hidden" name="si" value="localhost">
        </form>
      </div>
    </div>
  </div>
</header>
    <div class="outer">
      <section id="main"><article id="post-如何使用getopt-函数解析参数" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2014/07/18/如何使用getopt-函数解析参数/" class="article-date">
  <time datetime="2014-07-18T01:28:39.000Z" itemprop="datePublished">2014-07-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      如何使用getopt()函数解析参数
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>最近在写程序的过程中，把一部分时间都花费在程序对参数的处理上。今天听了学长说到getopt函数，才发现原来c里面还有一个专门解决参数处理的函数，查询了相关资料，这里简单总结一下。</p>
<p>使用<code>int main( int argc, char *argv[] )</code>或<code>int main( int argc, char **argv )</code>时，系统将把用户输入的参数通过argc和argv引入程序中，argc为参数的个数，argv是指向参数的指针数组，其中第一个参数为自身程序文件名。</p>
<p>这里我们使用getopt() 函数对传入的参数进行处理，getopt()位于 unistd.h 系统头文件中，函数原型可以在man中查到，大家可以使用下面指令查看getopt的man手册<code>man 3 getopt</code></p>
<p>getopt的函数原型如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;unistd.h&gt;</span><br><span class="line">int getopt(int argc, char * const argv[], const char *optstring);</span><br><span class="line"></span><br><span class="line">extern char *optarg;</span><br><span class="line">extern int optind, opterr, optopt;</span><br></pre></td></tr></table></figure></p>
<p>这里引用IBM对于其的解释，<a href="http://www.ibm.com/developerworks/cn/aix/library/au-unix-getopt.html" title="使用 getopt()进行命令行处理" target="_blank" rel="external">原文链接在这</a>。我对其中部分错误做了更改，</p>
<blockquote>
<p>给定了命令参数的数量 (argc)、指向这些参数的数组 (argv) 和选项字符串 (optstring) 后，getopt() 将返回第一个选项，并设置一些全局变量。使用相同的参数再次调用该函数时，它将返回下一个选项，并设置相应的全局变量。如果不再有识别到的选项，将返回 -1，此任务就完成了。</p>
<p>getopt() 所设置的全局变量包括：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">extern</span> <span class="keyword">char</span> *optarg;  <span class="comment">//选项的参数指针</span></span><br><span class="line">&gt; <span class="keyword">extern</span> <span class="keyword">int</span> optind,  <span class="comment">//下一次调用getopt的时，从optind存储的位置处重新开始检查选项。</span></span><br><span class="line">&gt; <span class="keyword">extern</span> <span class="keyword">int</span> opterr,  <span class="comment">//当opterr=0时，getopt不向stderr输出错误信息。</span></span><br><span class="line">&gt; <span class="keyword">extern</span> <span class="keyword">int</span> optopt;  <span class="comment">//当命令行选项字符不包括在optstring中或者选项缺少必要的参数时，该选项存储在optopt中，getopt返回'?'</span></span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
<p>对于每个选项，选项字符串 (optstring) 中都包含一个对应的字符。具有参数的选项后面跟有一个 : 字符。如果一个选项后面紧跟2个冒号（::），表示该选项和参数之间不使用空格隔开；</p>
<p>可以重复调用 getopt()，直到其返回 -1 为止；任何剩下的命令行参数通常视为文件名或程序相应的其他内容。</p>
</blockquote>
<p>我们知道，一般程序的选项分为两种：带关联值的和不带关联值的，</p>
<p>在解析参数的时候，我们希望的是：从一堆参数中把我们要的选项和选项关联值分别找到并存到相对应的地方供我们使用，并且把其他参数找出来供我们调用。</p>
<p>getopt完美实现这一点。</p>
<p>我们在测试的时候，定义了一个全局变量来存储参数值，<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="keyword">struct</span> parameter</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">int</span>     a;        <span class="comment">//参数a</span></span><br><span class="line">    <span class="keyword">int</span>     b;        <span class="comment">//参数b</span></span><br><span class="line">    <span class="keyword">char</span>    *b_pri;   <span class="comment">//参数b的关联值</span></span><br><span class="line">    <span class="keyword">int</span>     c;        <span class="comment">//参数c</span></span><br><span class="line">    <span class="keyword">char</span>    *c_pri;   <span class="comment">//参数c的关联值</span></span><br><span class="line">&#125; par;</span><br></pre></td></tr></table></figure></p>
<p>如果遇到了其他选项，getopt() 将显示一个错误消息，程序将在显示了使用方法消息后退出。因此optString应该为<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> *optstring = <span class="string">"ab:c::?"</span>;</span><br></pre></td></tr></table></figure></p>
<p>程序运行之前，我们先对参数初始化，设定其初始值。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数初始化</span></span><br><span class="line">opt.a = <span class="number">0</span>;</span><br><span class="line">opt.b = <span class="number">0</span>;</span><br><span class="line">opt.b_pri = <span class="literal">NULL</span>;</span><br><span class="line">opt.c = <span class="number">0</span>;</span><br><span class="line">opt.c_pri = <span class="literal">NULL</span>;</span><br></pre></td></tr></table></figure></p>
<p>接下来就简单的把参数使用getopt处理，最后输出最后的参数就行了，看看我们的测试程序。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">struct</span> parameter</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">int</span>       a;        <span class="comment">//参数a</span></span><br><span class="line">    <span class="keyword">int</span>       b;        <span class="comment">//参数b</span></span><br><span class="line">    <span class="keyword">char</span> *b_pri;        <span class="comment">//参数b的关联值</span></span><br><span class="line">    <span class="keyword">int</span>       c;        <span class="comment">//参数c</span></span><br><span class="line">    <span class="keyword">char</span> *c_pri;        <span class="comment">//参数c的关联值</span></span><br><span class="line">&#125;par;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">( <span class="keyword">int</span> argc, <span class="keyword">char</span> **argv )</span></span><br><span class="line"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i;        <span class="comment">//循环变量</span></span><br><span class="line">    par opt;    <span class="comment">//参数</span></span><br><span class="line">    <span class="keyword">int</span> flag = <span class="number">0</span>;    <span class="comment">//循环退出标志位</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//参数初始化</span></span><br><span class="line">    opt.a = <span class="number">0</span>;</span><br><span class="line">    opt.b = <span class="number">0</span>;</span><br><span class="line">    opt.b_pri = <span class="literal">NULL</span>;</span><br><span class="line">    opt.c = <span class="number">0</span>;</span><br><span class="line">    opt.c_pri = <span class="literal">NULL</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//参数检测</span></span><br><span class="line">    <span class="keyword">if</span> (argc == <span class="number">1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"您没有设置选项！\n"</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//输出未处理的参数</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"系统传入的参数为:"</span>);</span><br><span class="line">    <span class="keyword">for</span> ( i = <span class="number">1</span>; i &lt; argc; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"%s "</span>,argv[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//循环处理传入参数</span></span><br><span class="line">    <span class="keyword">while</span>(flag != <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//调用getopt处理参数</span></span><br><span class="line">        <span class="keyword">switch</span>(getopt( argc, argv, <span class="string">"ab:c::?"</span>))</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'a'</span>:</span><br><span class="line">                opt.a = <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'b'</span>:</span><br><span class="line">                opt.b = <span class="number">1</span>;</span><br><span class="line">                opt.b_pri = optarg;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'c'</span>:</span><br><span class="line">                opt.c = <span class="number">1</span>;</span><br><span class="line">                opt.c_pri = optarg;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">                flag = <span class="number">-1</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>( optind != argc)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"参数中非程序选项的有:"</span>);</span><br><span class="line">        <span class="keyword">for</span> (i = optind; i &lt; argc; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">"%s\t"</span>,argv[i]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//输出解析结果</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"解析到程序启动后启用的选项有："</span>);</span><br><span class="line">    <span class="keyword">if</span> (opt.a == <span class="number">1</span>)</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"a,"</span>);</span><br><span class="line">    <span class="keyword">if</span> (opt.b == <span class="number">1</span>)</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"b(参数为:%s),"</span>,opt.b_pri);</span><br><span class="line">    <span class="keyword">if</span> (opt.c == <span class="number">1</span>)</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"c(参数为:%s),"</span>,opt.c_pri);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//处理后，输出全部参数与原来对比</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"使用getopt后，系统参数变为为:"</span>);</span><br><span class="line">    <span class="keyword">for</span> ( i = <span class="number">1</span>; i &lt; argc; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"%s "</span>,argv[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line"></span><br><span class="line">    return <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>保存后，编译运行。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$ ./a.out -a -b 123 3 22 -h -c1</span><br><span class="line">系统传入的参数为:-a -b 123 3 22 -h -c1</span><br><span class="line">./a.out: invalid option -- &apos;h&apos;</span><br><span class="line">参数中非程序选项的有:3    22    </span><br><span class="line">解析到程序启动后启用的选项有：a,b(参数为:123),c(参数为:1),</span><br><span class="line">使用getopt后，系统参数变为为:-a -b 123 -h -c1 3 22</span><br></pre></td></tr></table></figure></p>
<p>其中，我们传入的参数被全部解析出来，非正常选项”-h”直接显示出来，如果大家不希望非正常参数显示出来，或者希望自己处理非正常参数，可以在设置getopt中全域变量opterr = 0，在optstring的时候不加入？，例如<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">opterr = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> *optstring = <span class="string">"ab:c::"</span>;</span><br></pre></td></tr></table></figure></p>
<p>那么程序在检测到未知选项会返回？，我们可以这样处理</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">opterr = <span class="number">0</span>;    <span class="comment">//getopt不输出错误参数</span></span><br><span class="line"></span><br><span class="line">...其他程序段...</span><br><span class="line"></span><br><span class="line"><span class="comment">//循环处理传入参数</span></span><br><span class="line"><span class="keyword">while</span>(flag != <span class="number">-1</span>)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//调用getopt处理参数</span></span><br><span class="line">    <span class="keyword">switch</span>(getopt( argc, argv, <span class="string">"ab:c::"</span>))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'a'</span>:</span><br><span class="line">            opt.a = <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'b'</span>:</span><br><span class="line">            opt.b = <span class="number">1</span>;</span><br><span class="line">            opt.b_pri = optarg;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'c'</span>:</span><br><span class="line">            opt.c = <span class="number">1</span>;</span><br><span class="line">            opt.c_pri = optarg;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'?'</span>:</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">"出现非正常选项：%c\n"</span>,optopt);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">            flag = <span class="number">-1</span>;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序源代码如下：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">struct</span> parameter</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">int</span>       a;        <span class="comment">//参数a</span></span><br><span class="line">    <span class="keyword">int</span>       b;        <span class="comment">//参数b</span></span><br><span class="line">    <span class="keyword">char</span> *b_pri;    <span class="comment">//参数b的关联值</span></span><br><span class="line">    <span class="keyword">int</span>       c;        <span class="comment">//参数c</span></span><br><span class="line">    <span class="keyword">char</span> *c_pri;    <span class="comment">//参数c的关联值</span></span><br><span class="line">&#125;par;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">( <span class="keyword">int</span> argc, <span class="keyword">char</span> **argv )</span></span><br><span class="line"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i;        <span class="comment">//循环变量</span></span><br><span class="line">    par opt;    <span class="comment">//参数</span></span><br><span class="line">    <span class="keyword">int</span> flag = <span class="number">0</span>;    <span class="comment">//循环退出标志位</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//参数初始化</span></span><br><span class="line">    opt.a = <span class="number">0</span>;</span><br><span class="line">    opt.b = <span class="number">0</span>;</span><br><span class="line">    opt.b_pri = <span class="literal">NULL</span>;</span><br><span class="line">    opt.c = <span class="number">0</span>;</span><br><span class="line">    opt.c_pri = <span class="literal">NULL</span>;</span><br><span class="line">    opterr = <span class="number">0</span>;    <span class="comment">//getopt不输出错误参数</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//参数检测</span></span><br><span class="line">    <span class="keyword">if</span> (argc == <span class="number">1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"您没有设置选项！\n"</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//输出未处理的参数</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"系统传入的参数为:"</span>);</span><br><span class="line">    <span class="keyword">for</span> ( i = <span class="number">1</span>; i &lt; argc; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"%s "</span>,argv[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//循环处理传入参数</span></span><br><span class="line">    <span class="keyword">while</span>(flag != <span class="number">-1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//调用getopt处理参数</span></span><br><span class="line">        <span class="keyword">switch</span>(getopt( argc, argv, <span class="string">"ab:c::"</span>))</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'a'</span>:</span><br><span class="line">                opt.a = <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'b'</span>:</span><br><span class="line">                opt.b = <span class="number">1</span>;</span><br><span class="line">                opt.b_pri = optarg;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'c'</span>:</span><br><span class="line">                opt.c = <span class="number">1</span>;</span><br><span class="line">                opt.c_pri = optarg;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="string">'?'</span>:</span><br><span class="line">                <span class="built_in">printf</span>(<span class="string">"出现非正常选项：%c\n"</span>,optopt);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">                flag = <span class="number">-1</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>( optind != argc)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"参数中非程序选项的有:"</span>);</span><br><span class="line">        <span class="keyword">for</span> (i = optind; i &lt; argc; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">"%s\t"</span>,argv[i]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//输出解析结果</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"解析到程序启动后启用的选项有："</span>);</span><br><span class="line">    <span class="keyword">if</span> (opt.a == <span class="number">1</span>)</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"a,"</span>);</span><br><span class="line">    <span class="keyword">if</span> (opt.b == <span class="number">1</span>)</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"b(参数为:%s),"</span>,opt.b_pri);</span><br><span class="line">    <span class="keyword">if</span> (opt.c == <span class="number">1</span>)</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"c(参数为:%s),"</span>,opt.c_pri);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//处理后，输出全部参数与原来对比</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"使用getopt后，系统参数变为为:"</span>);</span><br><span class="line">    <span class="keyword">for</span> ( i = <span class="number">1</span>; i &lt; argc; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"%s "</span>,argv[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"\n"</span>);</span><br><span class="line"></span><br><span class="line">    return <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这样的话，上面同样的参数下，运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$ ./a.out -a -b 123 3 22 -h -c1</span><br><span class="line">系统传入的参数为:-a -b 123 3 22 -h -c1</span><br><span class="line">出现非正常选项：h</span><br><span class="line">参数中非程序选项的有:3    22    </span><br><span class="line">解析到程序启动后启用的选项有：a,b(参数为:123),c(参数为:1),</span><br><span class="line">使用getopt后，系统参数变为为:-a -b 123 -h -c1 3 22</span><br></pre></td></tr></table></figure>
<p>ok了，其实还有一个比getopt更好的一个选择，就是getopt_long，它可以支持长选项，因为这篇博文呢针对getopt的，所以我就不多做介绍，大家可以查man手册，或者等待我不知道什么时候的下次更新吧。</p>

      
    </div>
    <footer class="article-footer">
      
        <a data-url="http://localhost/2014/07/18/如何使用getopt-函数解析参数/" data-id="cimvrqg220006kyfe7lj5y1oa" class="article-share-link">分享到</a>
      

      
        <a href="http://localhost/2014/07/18/如何使用getopt-函数解析参数/#ds-thread" class="article-comment-link">评论</a>
      

      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2014/07/24/使用C语言获取linux系统相关信息/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">
        
          使用C语言获取linux系统相关信息
        
      </div>
    </a>
  
  
    <a href="/2014/06/15/linux下挂载NTFS分区错误修复/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">linux下挂载NTFS分区错误修复</div>
    </a>
  
</nav>

  
</article>


  <section id="comments">
    <div id="ds-thread" class="ds-thread" data-thread-key="2014/07/18/如何使用getopt-函数解析参数/" data-title="如何使用getopt()函数解析参数" data-url="http://localhost/2014/07/18/如何使用getopt-函数解析参数/"></div>
  </section>
</section>
      
      <aside id="sidebar">
  
    
  
    
  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">五月 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">四月 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/12/">十二月 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/11/">十一月 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">七月 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">六月 2014</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">近期文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2015/05/01/Linux服务器配置与LNMP安装实录-1/">Linux服务器配置与LNMP安装实录---(1)</a>
          </li>
        
          <li>
            <a href="/2015/04/16/科学上网，简易教程/">科学上网，简易教程</a>
          </li>
        
          <li>
            <a href="/2014/12/17/记Fedora-21-Yun源配置和软件安装/">记Fedora 21 Yun源配置和软件安装</a>
          </li>
        
          <li>
            <a href="/2014/12/09/Linux运维文档之nginx【转】/">Linux运维文档之nginx【转】</a>
          </li>
        
          <li>
            <a href="/2014/11/26/CentOS-7安装完第一步：yum源配置/">CentOS 7安装完第一步：yum源配置</a>
          </li>
        
      </ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="http://xiguabaobao.com" target="_blank">主题作者</a>
          </li>
        
          <li>
            <a href="http://reqianduan.com" target="_blank">热前端</a>
          </li>
        
          <li>
            <a href="https://www.xiyoulinux.org" target="_blank">西邮linux兴趣小组</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
      
    </div>
    <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2016 wangbo<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
      .
      Theme by <a href="https://github.com/xiangming/landscape-plus" target="_blank">Landscape-plus</a>
    </div>
  </div>
</footer>
  </div>
  <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
  <!-- totop start -->
<div id="totop">
<a title="返回顶部"><img src="/img/scrollup.png"/></a>
</div>

<!-- totop end -->

<!-- 多说公共js代码 start -->
<script type="text/javascript">
var duoshuoQuery = {short_name:"idina"};
  (function() {
    var ds = document.createElement('script');
    ds.type = 'text/javascript';ds.async = true;
    ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
    ds.charset = 'UTF-8';
    (document.getElementsByTagName('head')[0]
     || document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
  </script>
<!-- 多说公共js代码 end -->


<!-- 百度分享 start -->

<!-- 百度分享 end -->

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>




<script src="/js/script.js"></script>

</div>
</body>
</html>
